import json

from fastapi import Request, APIRouter,Body
from typing import Optional
from core.Response import success
from models.models import Post, PostDteta
from schemas.posts import serialize_posts

router = APIRouter(prefix='')


@router.get("/", )
async def get_posts(request: Request, ):
    # 尝试从缓存中获取数据
    cached_posts = await request.app.state.cache.get('coasply')

    if cached_posts:
        print("从缓存中获取数据")
        return success(data=json.loads(cached_posts))

    # 获取 tags 标签为 1 的前 12 条数据
    recent_posts_queryset = await Post.filter(tags=1).order_by('id').limit(12)
    recent_posts = await serialize_posts(recent_posts_queryset)

    # 提取 recent_posts_queryset 中的 id 列表
    id_list = [post.id for post in recent_posts_queryset]

    # 根据 id 列表查询 PostDteta 表并获取 images 字段数据
    postdeta_queryset = await PostDteta.filter(id__in=id_list).order_by('id').limit(12)
    postdeta_images = {post.id: post.imageSrc[:4] for post in postdeta_queryset}

    # 将 postdeta_images 替换掉 posts 表中的 images 字段
    for post in recent_posts:
        print(postdeta_images.get(post.id, []))
        post.imageSrc = postdeta_images.get(post.id, [])

    # 将 Pydantic 模型转换为字典
    recent_posts_dict = [post.dict() for post in recent_posts]

    response_data = {

        'coasply': recent_posts_dict,

    }
    print(response_data)

    # 将数据序列化为 JSON 字符串并存入缓存
    await request.app.state.cache.set('coasply', json.dumps(response_data, default=str))

    return success(data=response_data)


@router.post("/", response_model=dict)
async def get_posts(request: Request, page: int = Body(..., description="当前页码"), page_size: int = Body(..., description="每页显示的帖子数量")):
    print(page, page_size,'='*50,Body())
    # 计算偏移量
    offset = page * page_size
    print(offset)

    # 检查缓存中是否存在对应页码的数据
    cache_key = f'coasply_page_{page}'
    cached_data = await request.app.state.cache.get(cache_key)

    if cached_data:
        print('加载缓存？？？')
        # 如果缓存中存在数据，直接返回缓存中的数据
        response_data = json.loads(cached_data)
    else:
        # 如果缓存中不存在数据，从数据库中获取数据
        # 获取最近发布的帖子
        recent_posts_queryset = await Post.filter(tags=1).order_by('id').limit(page_size).offset(offset)
        recent_posts = await serialize_posts(recent_posts_queryset)

        # 提取 recent_posts_queryset 中的 id 列表
        id_list = [post.id for post in recent_posts_queryset]

        # 根据 id 列表查询 PostDteta 表并获取 images 字段数据
        postdeta_queryset = await PostDteta.filter(id__in=id_list).order_by('id').limit(page_size)
        postdeta_images = {post.id: post.imageSrc[:4] for post in postdeta_queryset}

        # 将 postdeta_images 替换掉 posts 表中的 images 字段
        for post in recent_posts:
            # print(postdeta_images.get(post.id, []))
            post.imageSrc = postdeta_images.get(post.id, [])

        # 将 Pydantic 模型转换为字典
        recent_posts_dict = [post.dict() for post in recent_posts]

        response_data = {
            'coasply': recent_posts_dict,
        }
        # print(response_data)

        # 将数据序列化为 JSON 字符串并存入缓存
        await request.app.state.cache.set(cache_key, json.dumps(response_data, default=str))

    return success(data=response_data)